﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Queries.Regions.GetOne;

public class GetOneRegionsQueryHandler : IRequestHandler<GetOneRegionsQueryRequest, GetOneRegionsQueryResponse>
{
    private readonly IMapper _mapper;
    private readonly IRegionRepository _regionRepository;

    public GetOneRegionsQueryHandler(IMapper mapper, IRegionRepository regionRepository)
    {
        _mapper = mapper;
        _regionRepository = regionRepository;
    }

    public async Task<GetOneRegionsQueryResponse> Handle(GetOneRegionsQueryRequest request, CancellationToken cancellationToken)
    {
        var region = await _regionRepository.FirstOrDefaultWithParentAsync(x => x.Id == request.RegionId, cancellationToken);
        if (region == null) throw new NotFoundException($"Регион с id '{request.RegionId}' не найден");

        return _mapper.Map<GetOneRegionsQueryResponse>(region);
    }
}